<?php

	class Cookie 
	{
		private $name;
		private $expire;
		private $data;

		public function __construct() 
		{
			$this->name = '_traccia';
			$this->expire = 60 * 60 * 24; // 1 day
			$this->data = array();
			
			// get the old cookie, if any... or set some by default
            if(isset($_COOKIE[$this->name])) 
            {
                $this->data = unserialize(base64_decode($_COOKIE[$this->name]));
            }
            
            // need a session id
            if(!isset($this->data['session_id'])) 
            {
				self::set('session_id', md5( time() + rand(0,9999) ));
			}
		}

		public function set($name, $value) 
		{
		    $this->data[$name] = $value;
		    self::write();
		}

		public function get($name) 
		{
		    return (isset($this->data[$name]) ? $this->data[$name] : false);
		}

		public function remove($name) 
		{
		    unset($this->data[$name]);
		    self::write();
		}
		
		private function write() 
		{    
		    // get result
		    $value = base64_encode(serialize($this->data));//base64_encode($this->_serialize($this->data));
		    
		    // write to $_COOKIE
		    $_COOKIE[$this->name] = $value;
		    		    
		    //header('Set-Cookie: ' . $this->name . '=' . $value . '; Max-Age: ' . (time() + $this->expire) . '; Domain=' . $_SERVER['HTTP_HOST'] . '; Path=/');
		    setcookie($this->name, $value, time() + $this->expire, '/');
		}
		
		private function _serialize($data) 
		{    
		    // replace the back slashes, they will be restored later
		       
            if(is_array($data) || is_object($data)) 
            {
                foreach($data as $key => $value) 
                {
                    if(is_array($data)) 
                    {
                        $data[$key] = self::_serialize($value);
                    } 
                    else 
                    {
                        $data->$key = self::_serialize($value);
                    }
                }
            } 
            else 
            {
                $data = str_replace('\\', '{_backslash_}', $data);
            }
            return serialize($data);
		}
		
		private function _unserialize($data) 
		{    
            // restore the back slashes
            
            $data = @unserialize($data);
            
            if(is_array($data) || is_object($data)) 
            {
                foreach($data as $key => $value) 
                {
                    if(is_array($data)) 
                    {
                        $data[$key] = self::_unserialize($value);
                    } 
                    else 
                    {
                        $data->$key = self::_unserialize($value);
                    }
                }
                return $data;
            } 
            else 
            {
                return str_replace('{_backslash_}', '\\', $data);
            }
        }
	}

?>
